<template>
  <div class="unit-management">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/" class="breadcrumb-area">
      <el-breadcrumb-item to="/region/tree">区域</el-breadcrumb-item>
      <el-breadcrumb-item to="/region/community">社区</el-breadcrumb-item>
      <el-breadcrumb-item to="/region/building">楼栋</el-breadcrumb-item>
      <el-breadcrumb-item>单元管理</el-breadcrumb-item>
    </el-breadcrumb>



    <!-- 顶部工具栏 -->
    <el-card class="toolbar-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="社区">
          <el-select v-model="searchForm.communityId" placeholder="请选择社区" clearable style="width: 200px" @change="handleCommunityChange">
            <el-option 
              v-for="item in communityOptions" 
              :key="item.id" 
              :label="item.communityName" 
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="楼栋">
          <el-select v-model="searchForm.buildingId" placeholder="请选择楼栋" clearable style="width: 200px" @change="handleBuildingChange">
            <el-option 
              v-for="item in buildingOptions" 
              :key="item.id" 
              :label="item.buildingName" 
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 100px">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.unitName" placeholder="单元号/名称搜索" clearable style="width: 180px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 单元列表区 -->
    <el-row :gutter="16" class="unit-list-area">
      <el-col :span="6" v-for="unit in unitList" :key="unit.id">
        <el-card class="unit-card" shadow="hover">
          <div class="unit-card-header">
            <span class="unit-no">{{ unit.unitName }}</span>
            <el-tag :type="unit.status === 1 ? 'success' : 'danger'" size="small">
              {{ unit.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </div>
          <div class="unit-card-body">
            <div>单元编号：{{ unit.unitNo || '-' }}</div>
            <div>所属社区：{{ unit.communityName || '-' }}</div>
            <div>所属楼栋：{{ unit.buildingName || '-' }}</div>
            <div>楼层数：{{ unit.floorCount }}</div>
            <div>房间数：{{ unit.roomCount || 0 }}</div>
            <div>户数：{{ unit.householdCount || 0 }}</div>
            <div>电梯：{{ unit.hasElevator ? '有' : '无' }}{{ unit.hasElevator && unit.elevatorCount ? `(${unit.elevatorCount}台)` : '' }}</div>
            <div>门禁：{{ getDoorAccessTypeText(unit.doorAccessType) }}</div>
            <div>管理员：{{ unit.managerName || '-' }}</div>
          </div>
          <div class="unit-card-actions">
            <el-button size="small" @click="handleDetail(unit)">详情</el-button>
            <el-button size="small" type="primary" @click="handleEdit(unit)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(unit)">删除</el-button>
            <el-button size="small" @click="handleHousehold(unit)">房户管理</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 分页 -->
    <div class="pagination-area">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑弹窗 -->
    <UnitForm v-model:visible="formVisible" :form-data="currentUnit" @success="handleFormSuccess" />
    <!-- 详情弹窗 -->
    <UnitDetail v-model:visible="detailVisible" :unit-id="detailUnitId" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessageBox } from 'element-plus'
import { unitApi } from '@/api/unit'
import { buildingApi } from '@/api/building'
import { communityApi } from '@/api/community'
import UnitForm from './UnitForm.vue'
import UnitDetail from './UnitDetail.vue'
import { useRouter } from 'vue-router'
import { hasPermission } from '@/utils/permission'
import { showMessage } from '@/utils/message'

const router = useRouter()

const searchForm = reactive({
  communityId: undefined as any,
  buildingId: undefined as any,
  status: undefined as any,
  unitName: ''
})

const pagination = reactive({
  current: 1,
  size: 12,
  total: 0
})

const unitList = ref<any[]>([])
const communityOptions = ref<any[]>([])
const buildingOptions = ref<any[]>([])
const formVisible = ref(false)
const detailVisible = ref(false)
const currentUnit = ref<any>(null)
const detailUnitId = ref<number | null>(null)

// 初始化权限信息，防止未定义报错
const userPermissionInfo = ref({
  isSuperAdmin: false,
  hasPropertyCompany: false,
  propertyCompanyId: null as number | null,
  propertyCompanyName: ''
})

// 权限判断computed
const isSuperAdmin = computed(() => {
  return userPermissionInfo.value.isSuperAdmin
})

const hasPropertyCompany = computed(() => {
  return userPermissionInfo.value.hasPropertyCompany
})

const canManage = computed(() => isSuperAdmin.value || hasPropertyCompany.value)


// 加载用户权限信息
const loadUserPermissionInfo = async () => {
  try {
    // 首先确保公司信息是最新的
    // await userStore.checkAndUpdateCompanyInfo() // 移除userStore调用
    
    // const permission = await userStore.getUserDataScope() // 移除userStore调用
    // userPermissionInfo.value.isSuperAdmin = permission.isSuperAdmin
    // userPermissionInfo.value.hasPropertyCompany = permission.hasPropertyCompany
    // userPermissionInfo.value.propertyCompanyId = permission.companyId
    // userPermissionInfo.value.propertyCompanyName = permission.companyName
  } catch (error) {
    // userPermissionInfo.value.isSuperAdmin = false
    // userPermissionInfo.value.hasPropertyCompany = false
    // userPermissionInfo.value.propertyCompanyId = null
    // userPermissionInfo.value.propertyCompanyName = ''
  }
}

// 加载社区选项
const loadCommunityOptions = async () => {
  try {
    const res = await communityApi.getCommunityList({})
    communityOptions.value = (res.data || []).filter((item: any) => 
      item && typeof item.id === 'number' && item.id > 0 && 
      item.communityName && typeof item.communityName === 'string'
    )
  } catch (e) {
    showMessage({ type: 'error', message: '加载社区失败' })
    communityOptions.value = []
  }
}

// 加载楼栋选项
const loadBuildingOptions = async (communityId: number) => {
  try {
    if (!communityId) {
      buildingOptions.value = []
      return
    }
    
    // 使用下拉框专用接口，返回数组格式数据
    const res = await buildingApi.getBuildingsByCommunity(communityId)
    buildingOptions.value = (res.data || []).filter((item: any) => 
      item && typeof item.id === 'number' && item.id > 0 && 
      item.buildingName && typeof item.buildingName === 'string'
    )
  } catch (e) {
    showMessage({ type: 'error', message: '加载楼栋失败' })
    buildingOptions.value = []
  }
}

// 社区选择变化处理
const handleCommunityChange = (communityId: any) => {
  searchForm.buildingId = undefined // 清空楼栋选择
  if (communityId) {
    loadBuildingOptions(communityId)
  } else {
    buildingOptions.value = []
  }
  handleSearch()
}

// 楼栋选择变化处理
const handleBuildingChange = (buildingId: any) => {
  handleSearch()
}

const loadUnitList = async () => {
  try {
    const params: any = {
      current: pagination.current,
      size: pagination.size
    }
    
    // 只添加有值的搜索条件
    if (searchForm.communityId) {
      params.communityId = searchForm.communityId
    }
    if (searchForm.buildingId) {
      params.buildingId = searchForm.buildingId
    }

    if (searchForm.status !== undefined) {
      params.status = searchForm.status
    }
    if (searchForm.unitName) {
      params.unitName = searchForm.unitName
    }
    
    const res = await unitApi.getUnitPage(params)
    unitList.value = res.data.records || []
    pagination.total = res.data.total || 0
  } catch (e) {
    showMessage({ type: 'error', message: '加载单元列表失败' })
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadUnitList()
}

const handleReset = () => {
      Object.assign(searchForm, {
      communityId: undefined,
      buildingId: undefined,
      status: undefined,
      unitName: ''
    })
  buildingOptions.value = []
  handleSearch()
}

const handleAdd = () => {
  currentUnit.value = null
  formVisible.value = true
}

const handleEdit = async (unit: any) => {
  try {
    // 先获取完整的单元详情数据
    const response = await unitApi.getUnitDetail(unit.id)
    if (response.data) {
      currentUnit.value = response.data
    } else {
      // 如果获取详情失败，使用列表数据
      currentUnit.value = { ...unit }
    }
    formVisible.value = true
  } catch (error) {
    console.error('获取单元详情失败:', error)
    // 获取详情失败时，使用列表数据
    currentUnit.value = { ...unit }
    formVisible.value = true
  }
}

const handleDelete = async (unit: any) => {
  try {
    await ElMessageBox.confirm(`确定要删除单元"${unit.unitName}"吗？`, '提示', { type: 'warning' })
    await unitApi.deleteUnit(unit.id)
    showMessage({ type: 'success', message: '删除成功' })
    loadUnitList()
  } catch (e) {
    if (e !== 'cancel') showMessage({ type: 'error', message: '删除失败' })
  }
}

const handleDetail = (unit: any) => {
  detailUnitId.value = unit.id
  detailVisible.value = true
}

const handleHousehold = (unit: any) => {
  router.push(`/region/household?unitId=${unit.id}`)
}

const handleFormSuccess = () => {
  formVisible.value = false
  loadUnitList()
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  loadUnitList()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadUnitList()
}

// 获取门禁类型文本
const getDoorAccessTypeText = (type: number) => {
  const typeMap: Record<number, string> = {
    1: '密码',
    2: '刷卡',
    3: '人脸识别',
    4: '指纹'
  }
  return typeMap[type] || '未知'
}

onMounted(() => {
  loadUserPermissionInfo(); // 权限信息
  loadCommunityOptions(); // 社区选项
  loadUnitList(); // 单元列表
});
</script>

<style lang="scss" scoped>
.unit-management {
  padding: 24px;
  .breadcrumb-area {
    margin-bottom: 16px;
  }
  .toolbar-card {
    margin-bottom: 16px;
  }
  .unit-list-area {
    margin-bottom: 16px;
  }
  .unit-card {
    margin-bottom: 16px;
    .unit-card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 8px;
    }
    .unit-card-body {
      font-size: 14px;
      margin-bottom: 8px;
      div {
        margin-bottom: 4px;
      }
    }
    .unit-card-actions {
      display: flex;
      gap: 8px;
      flex-wrap: wrap;
    }
  }
  .pagination-area {
    text-align: right;
    margin-top: 16px;
  }
}
</style> 